<!-- Copyright (c) 2014 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. -->

<link rel="import" href="../common/cr-button.html">
<link rel="import" href="../common/cr-cursor-manager.html">
<link rel="import" href="../common/cr-keyboard.html">
<link rel="import" href="../common/cr-toolbar.html">
<link rel="import" href="../components/cr-issue-list.html">
<link rel="import" href="../components/cr-user-autocomplete.html">

<polymer-element name="cr-search-view">
    <template>
        <link rel="stylesheet" href="../common/common.css">
        <link rel="stylesheet" href="../common/forms.css">
        <style>
            :host { display: block; }

            .search-layout {
                display: -webkit-flex;
                display: flex;
            }

            .search-form {
                width: 400px;
                flex-shrink: 0;
                -webkit-flex-shrink: 0;
            }

            .search-results {
                flex: 1;
            }

            .search-results header {
                display: -webkit-flex;
                display: flex;
                align-items: center;
                -webkit-align-items: center;
                margin-right: 16px;
            }

            .search-results h2 {
                flex: 1;
                -webkit-flex: 1;
            }

            cr-issue-list {
                margin: 20px 16px 0 16px;
            }

            p {
                margin-left: 16px;
                font-size: 1.2em;
                margin-top: 6px;
            }

            @media (max-width: 500px) {
                .search-form {
                    width: auto;
                }

                .search-layout {
                    display: block;
                }
            }
        </style>
        <h1 class="app-header">Search</h1>

        <div class="search-layout">
            <div class="search-form">
                <h2>Query</h2>
                <fieldset class="form-fields" disabled?="{{ disabled }}">
                    <div class="form-row">
                        <label class="form-label" for="owner">Owner</label>
                        <div class="form-field">
                            <cr-user-autocomplete id="ownerAutocomplete" value="{{ query.owner }}">
                                <input type="text" id="owner" value="{{ query.owner }}" autocomplete="off">
                            </cr-user-autocomplete>
                        </div>
                    </div>
                    <div class="form-row">
                        <label class="form-label" for="reviewer">Reviewer</label>
                        <div class="form-field">
                            <cr-user-autocomplete id="reviewerAutocomplete" value="{{ query.reviewer }}">
                                <input type="text" id="reviewer" value="{{ query.reviewer }}" autocomplete="off">
                            </cr-user-autocomplete>
                        </div>
                    </div>
                    <div class="form-row">
                        <label class="form-label" for="cc">CC</label>
                        <div class="form-field">
                            <cr-user-autocomplete id="ccAutocomplete" value="{{ query.cc }}">
                                <input type="text" id="cc" value="{{ query.cc }}" autocomplete="off">
                            </cr-user-autocomplete>
                        </div>
                    </div>
                    <div class="form-row">
                        <label class="form-label" for="sort">Sort by</label>
                        <div class="form-field">
                            <select id="sort" value="{{ query.sort }}">
                                <option value="modified" selected>Last modified</option>
                                <option value="created">Created</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <label class="form-label" for="orderby">Order</label>
                        <div class="form-field">
                            <select id="orderby" value="{{ query.order }}">
                                <option value="descending" selected>Newest first</option>
                                <option value="ascending">Oldest first</option>
                            </select>
                        </div>
                    </div>
                </fieldset>
                <cr-toolbar>
                    <button is="cr-button" primary on-tap="{{ search }}">Search</button>
                </cr-toolbar>
            </div>
            <div class="search-results">
                <header>
                    <h2>Issues</h2>
                    <template if="{{ result && result.issues.length == query.limit }}">
                        <a is="cr-action" on-tap="{{ handleNextPage }}">Next</a>
                    </template>
                </header>
                <cr-issue-list issues="{{ result.issues }}"></cr-issue-list>
                <template if="{{ result && !result.issues.length }}">
                    <p>No results.</p>
                </template>
                <template if="{{ sending }}">
                    <p>Searching...</p>
                </template>
            </div>
        </div>

        <cr-cursor-manager id="cursorManager"
                           stopSelector="cr-issue-list /deep/ .issue"
                           ></cr-cursor-manager>
        <cr-keyboard on-key-j="{{ handleNextIssueKey }}"
                     on-key-k="{{ handlePreviousIssueKey }}"
                     on-key-down="{{ handleNextIssueKey }}"
                     on-key-up="{{ handlePreviousIssueKey }}"
                     on-key-o="{{ handleOpenTargetIssueKey }}"
                     global></cr-keyboard>
        <cr-keyboard on-key-enter="{{ handleEnterKey }}"></cr-keyboard>
    </template>
    <script>
        Polymer({
            created: function() {
                this.result = null;
                this.query = {
                    owner: "",
                    reviewer: "",
                    cc: "",
                    sort: "modified",
                    order: "descending",
                    limit: Search.DEFAULT_LIMIT,
                };
                this.queryId = 0;
                this.sending = false;
            },
            attached: function() {
                this.fire("title-change", {
                    value: "Search issues",
                });
                var query = Object.fromQueryString(window.location);
                if (!Object.isEmpty(query)) {
                    Object.merge(this.query, query);
                    this.search();
                }
            },
            handleEnterKey: function() {
                if (this.$.ownerAutocomplete.active
                    || this.$.reviewerAutocomplete.active
                    || this.$.ccAutocomplete.active) {
                    return;
                }
                this.search();
            },
            handleNextPage: function() {
                var self = this;
                if (!this.result)
                    return;
                var queryId = ++this.queryId;
                var cursor = this.result.cursor;
                this.result.findNext().then(function(result) {
                    self.query.cursor = cursor;
                    self.updateUrl();
                    if (self.queryId == queryId)
                        self.updateResult(result);
                });
            },
            search: function() {
                var self = this;
                this.$.ownerAutocomplete.resetAutocomplete();
                this.$.reviewerAutocomplete.resetAutocomplete();
                this.$.ccAutocomplete.resetAutocomplete();
                this.updateUrl();
                var queryId = ++this.queryId;
                this.query.cursor = "";
                this.result = null;
                this.sending = true;
                Search.findIssues(this.query).then(function(result) {
                    if (queryId == self.queryId)
                        self.updateResult(result);
                }).catch(function(error) {
                    console.log(error);
                    // If there's no JSON response we assume it meant there was
                    // no results. This isn't really true, but the server doesn't
                    // have a good JSON API.
                    if (queryId == self.queryId)
                        self.updateResult(new SearchResult([], ""));
                }).either(function() {
                    if (queryId == self.queryId)
                        self.sending = false;
                });
            },
            updateUrl: function() {
                var queryString = Object.toQueryString(this.query);
                queryString = queryString.replace(/\+/g, "%20");
                var newUrl = window.location.pathname + "?" + queryString;
                    + window.location.hash;
                var oldUrl = window.location.pathname + window.location.search;
                    + window.location.hash;
                if (oldUrl == newUrl)
                    return;
                window.history.pushState(null, null, newUrl);
            },
            updateResult: function(result) {
                this.result = result;
                this.cursor = result.cursor;
                this.$.cursorManager.resetStops();
            },
            handleNextIssueKey: function(event) {
                this.$.cursorManager.next(event);
            },
            handlePreviousIssueKey: function(event) {
                this.$.cursorManager.previous(event);
            },
            handleOpenTargetIssueKey: function(event) {
                this.$.cursorManager.open(event);
            },
        });
    </script>
</polymer-element>
